/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOUser;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 *
 * @author Tri
 */
public class DTUser {
    private static DTUser instance = null;
    public static DTUser sharedInstance() {
        if(instance == null) {
            instance = new DTUser();
        }
        return instance;
    }
    
    public static final String TABLE_NAME = "User";
    MongoOperations m_mongoOperations;
    private DTUser() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public void insert(DTUser user) {
        m_mongoOperations.save(user, TABLE_NAME);
    }
    
    public boolean update(DOUser user) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOUser.KEY_USER_ID).is(user.getUserID()));
        DOUser resultQuery = m_mongoOperations.findOne(query, DOUser.class);
        if(resultQuery != null) {
            Update update = new Update();
            update.set(DOUser.KEY_AVATAR, user.avatarURL);
            update.set(DOUser.KEY_CURRENT_LVL, user.currentLevel);
            update.set(DOUser.KEY_LATEST_LVL, user.latestLevel);
            update.set(DOUser.KEY_LIVES, user.lives);
            update.set(DOUser.KEY_TIME_TO_GAIN_LIVE, user.timeToGainTime);
            update.set(DOUser.KEY_FRIENDS_LIST, user.getFriendsList());
            update.set(DOUser.KEY_ITEMS_LIST, user.getItemsList());
            
            m_mongoOperations.updateFirst(query, update, DOUser.class);
            return true;
        }
        return false;
    }
    
    public DOUser getUserInfo(String userID) {
        DOUser user = null;
        
        Query query = new Query();
        query.addCriteria(Criteria.where(DOUser.KEY_USER_ID).is(userID));
        user = m_mongoOperations.findOne(query, DOUser.class);
        return user;
    }
}
